<!--
 * @Author: byron
 * @Date: 2022-01-06 00:12:14
 * @LastEditTime: 2022-01-08 22:39:20
-->
<template>
    <div id="rocket">
        <span v-show="btnFlag" @click="backTop"> </span>
    </div>
</template>

<script>
export default {
    components: {},
    props: {},
    data() {
        return {
            btnFlag: 0,
        }
    },
    watch: {},
    computed: {},

    methods: {
        // 点击图片回到顶部方法，加计时器是为了过渡顺滑
        backTop() {
            const that = this
            let timer = setInterval(() => {
                let ispeed = Math.floor(-that.scrollTop / 5)
                console.log(that.scrollTop)
                document.documentElement.scrollTop = document.body.scrollTop =
                    that.scrollTop + ispeed
                if (that.scrollTop === 0) {
                    clearInterval(timer)
                }
            }, 16)
        },

        // 为了计算距离顶部的高度，当高度大于60显示回顶部图标，小于60则隐藏
        scrollToTop() {
            const that = this
            let scrollTop =
                window.pageYOffset ||
                document.documentElement.scrollTop ||
                document.body.scrollTop
            that.scrollTop = scrollTop
            if (that.scrollTop > 60) {
                that.btnFlag = true
            } else {
                that.btnFlag = false
            }
        },
    },
    created() {},
    //初始化页面之后，再对dom节点进行相关操作
    mounted() {
        window.addEventListener('scroll', this.scrollToTop)
    },
    destroyed() {
        window.removeEventListener('scroll', this.scrollToTop)
    },
}
</script>
<style lang="less" scoped>
#rocket {
    position: fixed;
    z-index: 999;
    bottom: 60px;
    right: 50px;
    cursor: pointer;
    span {
        display: inline-block;
        width: 26px;
        height: 48px;
        background: url('../static/imges/rocket.png') no-repeat 50% 0;
    }
    span:hover {
        background-position: 50% 80%;
    }
}
</style>
